<template>
  <div class="product-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="primary" @click="navigateToOrders">查看订单信息</el-button>
        </div>
      </template>
      
      <AddProductForm 
        v-model:dialogVisible="dialogVisible"
        @refresh="fetchProducts"
      />

      <el-table :data="products" :row-key="row => row.id" style="width: 100%">
        <!-- 根据用户角色动态显示列 -->
        <el-table-column prop="name" label="商品名称" />
        <el-table-column v-if="userStore.role !== 'customer'" prop="supplier" label="供应商" />
        <el-table-column prop="price" label="价格（元）" />
        <el-table-column prop="description" label="商品描述" />
        <el-table-column v-if="userStore.role === 'customer'" prop="category" label="分类" />
        <el-table-column v-if="userStore.role === 'sales'" prop="minStock" label="最低库存预警" />

        <el-alert
          title="数据绑定状态"
          type="info"
          :description="`当前加载商品数量：${products.length}`"
          :closable="false"
        />

        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="success" link @click="handleOrder(row)">立即下单</el-button>
          </template>
        </el-table-column>

        <el-dialog
          title="填写购买信息"
          v-model:visible="orderDialogVisible"
          width="50%"
          @close="resetOrderForm">
          <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="orderForm.productName" disabled/>
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="orderForm.customerName"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="orderForm.phone"/>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="orderForm.address"/>
            </el-form-item>
            <el-form-item label="购买数量" prop="quantity">
              <el-input-number v-model="orderForm.quantity" :min="1" :max="orderForm.stock"/>
            </el-form-item>
            <el-form-item label="总价（元）" prop="totalPrice">
              <el-input v-model="orderForm.totalPrice" disabled/>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="orderDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitOrder">提交订单</el-button>
            </span>
          </template>
        </el-dialog>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import mockData from '@/data/mockData.json'
import AddProductForm from '@/components/AddProductForm.vue'
import { useUserStore } from '@/stores/user' // 引入用户store获取角色信息
import { useProductStore } from '@/stores/productStore' // 引入productStore统一数据源
const userStore = useUserStore()

const router = useRouter()
const products = ref([])
const dialogVisible = ref(false)
const orderDialogVisible = ref(false)
const orderForm = ref({
  productName: '',
  customerName: '',
  phone: '',
  address: '',
  quantity: 1,
  price: 0,
  totalPrice: 0,
  stock: 0
})
const orderRules = ref({
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入购买数量', trigger: 'blur' }]
})

onMounted(() => {
  fetchProducts()
})

const navigateToOrders = () => {
  router.push('/admin/orders').catch(error => {
    ElMessage.error(`跳转订单页失败: ${error.message}`)
  })
}

async function fetchProducts() {
  try {
    const productStore = useProductStore()
    await productStore.initialize()
    products.value = productStore.products
    ElMessage.success('从统一数据源加载商品数据')
  } catch (error) {
    console.error('Failed to fetch products:', error)
    ElMessage.error('获取商品列表失败')
  }
}

function handleAdd() {
  dialogVisible.value = true
}

function handleOrder(row) {
  if (!row) return
  orderDialogVisible.value = true
  nextTick(() => {
    console.log('[DEBUG] 强制更新后，orderDialogVisible状态:', orderDialogVisible.value)
  })
  orderForm.value = {
    productName: row.name,
    customerName: '',
    phone: '',
    address: '',
    price: row.price,
    stock: row.stock,
    quantity: 1,
    totalPrice: row.price
  }
}

function resetOrderForm() {
  orderForm.value = {
    productName: '',
    customerName: '',
    phone: '',
    address: '',
    quantity: 1,
    price: 0,
    totalPrice: 0,
    stock: 0
  }
}

async function submitOrder() {
  const formRef = document.querySelector('[ref="orderFormRef"]')?.__vue__
  if (!formRef) return
  await formRef.validate((valid) => {
    if (!valid) return ElMessage.warning('请完善订单信息')
    console.log('提交订单数据:', orderForm.value)
    ElMessage.success('订单提交成功')
    orderDialogVisible.value = false
  })
}

function handleEdit(row) {
  dialogVisible.value = true
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '警告', { type: 'warning' })
    await axios.delete(`/api/products/${row.id}/`)
    ElMessage.success('删除成功')
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete product:', error)
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog {
  z-index: 9999 !important;
}
.product-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>